<template>
    <div class="user-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="query" :inline="true" class="search-form">
                            <el-form-item label="用户名:">
                                <el-input 
                                    v-model="query.username" 
                                    placeholder="输入用户名" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="手机号:">
                                <el-input 
                                    v-model="query.phone" 
                                    placeholder="输入手机号" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="状态:">
                                <el-select 
                                    v-model="query.status" 
                                    placeholder="请选择状态" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="启用" :value="1" />
                                    <el-option label="禁用" :value="0" />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询结果</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增用户按钮 -->
        <div class="add-section">
            <el-button type="primary" :icon="CirclePlusFilled" @click="handleAdd">新增用户</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="username" label="用户名"/>
                    <el-table-column prop="realName" label="真实姓名">
                        <template #default="{ row }">
                            {{ row.realName || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号" width="140">
                        <template #default="{ row }">
                            {{ row.phone || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="gender" label="性别" width="80" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getGenderTagType(row.gender)">
                                {{ getGenderText(row.gender) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="groupName" label="用户组" width="120">
                        <template #default="{ row }">
                            {{ getUserGroupName(row.groupId) || row.groupName || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getStatusTagType(row.status)">
                                {{ getStatusText(row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatTime(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
                            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ page.total }}条记录,当前在第{{ page.index }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="page.index"
                        :page-size="page.size"
                        :total="page.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="changePage"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>

        <!-- 新增/编辑弹窗 -->
        <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" />
        </el-dialog>

        <!-- 查看详情弹窗 -->
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { User } from '@/types/user';
import { getUserPage, updateUser, saveUser, deleteUser, getUserById } from '@/api/system/user';
import { getUserGroupList } from '@/api/system/userGroup';
import { formatTime } from '@/utils/time';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';

// 查询相关
const query = reactive({
    username: '',
    phone: '',
    status: null as number | null
});

const handleSearch = () => {
    // 搜索时重置到第一页
    page.index = 1;
    getData();
};

const handleReset = () => {
    // 重置搜索条件
    query.username = '';
    query.phone = '';
    query.status = null;
    // 重置到第一页并重新加载数据
    page.index = 1;
    getData();
};

// 表格相关
const loading = ref(false);
const page = reactive({
    index: 1,
    size: 10,
    total: 0,
})
const tableData = ref<User[]>([]);

const getData = async () => {
    loading.value = true;
    try {
        // 构建查询参数
        const params = {
            current: page.index,  // 当前页码
            size: page.size,      // 每页大小
            // 搜索条件
            ...(query.username && { username: query.username }),
            ...(query.phone && { phone: query.phone }),
            ...(query.status !== null && { status: query.status })
        };
        
        console.log('请求参数:', params);
        
        const res = await getUserPage(params);
        console.log('API响应:', res);
        
        // 处理不同的响应数据结构
        const responseData = res as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            // 标准分页响应结构
            tableData.value = responseData.data.records || responseData.data.list || [];
            page.total = responseData.data.total || responseData.data.pageTotal || 0;
            
            // 如果数据为空，显示提示
            if (tableData.value.length === 0) {
                ElMessage.info('暂无用户数据');
            }
        } else {
            // 处理错误响应
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取用户数据失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            page.total = 0;
        }
    } catch (error) {
        console.error('获取用户数据失败:', error);
        ElMessage.error('网络错误，请稍后重试');
        tableData.value = [];
        page.total = 0;
    } finally {
        loading.value = false;
    }
};

const changePage = (val: number) => {
    page.index = val;
    getData();
};

const handleSizeChange = (size: number) => {
    page.size = size;
    page.index = 1;
    getData();
};

// 获取性别文本
const getGenderText = (gender: number) => {
    const genderMap: { [key: number]: string } = {
        0: '未知',
        1: '男',
        2: '女'
    };
    return genderMap[gender] || '未知';
};

// 获取性别标签类型
const getGenderTagType = (gender: number) => {
    const typeMap: { [key: number]: string } = {
        0: 'info',
        1: 'primary',
        2: 'warning'
    };
    return typeMap[gender] || 'info';
};

// 获取状态文本
const getStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '禁用',
        1: '启用'
    };
    return statusMap[status] || '未知';
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
    const typeMap: { [key: number]: string } = {
        0: 'danger',
        1: 'success'
    };
    return typeMap[status] || 'info';
};

// 用户组数据
const userGroupOptions = ref<Array<{label: string, value: string}>>([]);

// 获取用户组列表
const loadUserGroups = async () => {
    try {
        const res = await getUserGroupList();
        const responseData = res as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            userGroupOptions.value = responseData.data.map((item: any) => ({
                label: item.groupName || item.name || '未命名用户组',
                value: item.id || item.groupId
            }));
        }
    } catch (error) {
        console.error('获取用户组列表失败:', error);
        ElMessage.error('获取用户组列表失败');
    }
};

// 更新用户组选项
const updateUserGroupOptions = () => {
    const userGroupField = options.value.list.find(item => item.prop === 'groupId');
    if (userGroupField) {
        userGroupField.opts = userGroupOptions.value;
    }
};

// 根据用户组ID获取用户组名称
const getUserGroupName = (groupId: string) => {
    const userGroup = userGroupOptions.value.find(item => item.value === groupId);
    return userGroup ? userGroup.label : '';
};


// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '用户名', prop: 'username', required: true },
        { type: 'input', label: '密码', prop: 'password', required: true, placeholder: '请输入密码' },
        { type: 'input', label: '真实姓名', prop: 'realName', required: false },
        { 
            type: 'input', 
            label: '手机号', 
            prop: 'phone', 
            required: true,
            placeholder: '请输入11位手机号',
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号格式'
        } as any,
        { 
            type: 'select', 
            label: '性别', 
            prop: 'gender', 
            required: false,
            opts: [
                { label: '未知', value: 0 },
                { label: '男', value: 1 },
                { label: '女', value: 2 }
            ]
        },
        { 
            type: 'select', 
            label: '状态', 
            prop: 'status', 
            required: false,
            opts: [
                { label: '禁用', value: 0 },
                { label: '启用', value: 1 }
            ]
        },
        { 
            type: 'select', 
            label: '用户组', 
            prop: 'groupId', 
            required: false,
            opts: userGroupOptions.value
        },
    ]
})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = async (row: User) => {
    try {
        // 显示加载状态
        loading.value = true;
        
        // 加载用户组数据
        await loadUserGroups();
        // 更新表单配置中的用户组选项
        updateUserGroupOptions();
        
        // 根据ID查询用户详情
        const res = await getUserById(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            // 使用API返回的最新数据
            rowData.value = { ...responseData.data };
            isEdit.value = true;
            visible.value = true;
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取用户详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取用户详情失败:', error);
        ElMessage.error('获取用户详情失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

const updateData = async (formData: any) => {
    try {
        loading.value = true;
        
        if (isEdit.value) {
            // 编辑用户
            const res = await updateUser(formData);
            const responseData = res as any;
            if (responseData && responseData.code === 200) {
                ElMessage.success('用户更新成功');
                closeDialog();
                getData();
            } else {
                const errorMsg = (responseData && responseData.msg) || '更新用户失败';
                ElMessage.error(errorMsg);
            }
        } else {
            // 新增用户
            const res = await saveUser(formData);
            const responseData = res as any;
            if (responseData && responseData.code === 200) {
                ElMessage.success('用户创建成功');
    closeDialog();
    getData();
            } else {
                const errorMsg = (responseData && responseData.msg) || '创建用户失败';
                ElMessage.error(errorMsg);
            }
        }
    } catch (error) {
        console.error('保存用户失败:', error);
        ElMessage.error('操作失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
    rowData.value = {}; // 清空表单数据
};

// 新增用户
const handleAdd = async () => {
    // 加载用户组数据
    await loadUserGroups();
    // 更新表单配置中的用户组选项
    updateUserGroupOptions();
    
    rowData.value = {
        username: '',
        password: '',
        realName: '',
        phone: '',
        gender: 0,
        status: 1, // 默认启用
        groupId: ''
    };
    isEdit.value = false;
    visible.value = true;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});
const handleView = async (row: User) => {
    try {
        // 显示加载状态
        loading.value = true;
        
        // 根据ID查询用户详情
        const res = await getUserById(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            const userData = responseData.data;
            
            // 格式化性别显示
            const formatGender = (gender: number) => {
                const genderMap: { [key: number]: string } = {
                    0: '未知',
                    1: '男',
                    2: '女'
                };
                return genderMap[gender] || '未知';
            };

            // 格式化状态显示
            const formatStatus = (status: number) => {
                const statusMap: { [key: number]: string } = {
                    0: '禁用',
                    1: '启用'
                };
                return statusMap[status] || '未知';
            };

            // 处理行数据，格式化显示
            const formattedRow = {
                ...userData,
                gender: formatGender(userData.gender),
                status: formatStatus(userData.status),
                createTime: formatTime(userData.createTime)
            };

            viewData.value.row = formattedRow;
            viewData.value.list = [
                {
                    prop: 'username',
                    label: '用户名',
                },
                {
                    prop: 'realName',
                    label: '真实姓名',
                },
                {
                    prop: 'phone',
                    label: '手机号',
                },
                {
                    prop: 'gender',
                    label: '性别',
                },
                {
                    prop: 'groupName',
                    label: '用户组',
                },
                {
                    prop: 'status',
                    label: '状态',
                },
                {
                    prop: 'createTime',
                    label: '创建时间',
                },
            ];
            visible1.value = true;
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取用户详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取用户详情失败:', error);
        ElMessage.error('获取用户详情失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 删除相关
const handleDelete = async (row: User) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除用户 "${row.username}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        // 调用删除API
        loading.value = true;
        const res = await deleteUser(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200) {
    ElMessage.success('删除成功');
            getData(); // 刷新列表
        } else {
            const errorMsg = (responseData && responseData.msg) || '删除失败';
            ElMessage.error(errorMsg);
        }
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除用户失败:', error);
            ElMessage.error('删除失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
}

// 初始化数据
getData();
// 初始化用户组数据
loadUserGroups();
</script>

<style scoped>
.user-list-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
    margin-bottom: 20px;
}

/* 新增按钮区域 */
.add-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
}

.search-left {
    flex: 1;
}

.search-right {
    display: flex;
    gap: 12px;
    margin-left: 20px;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

/* 表格区域样式 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域样式 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
    width: 100%;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    gap: 20px;
    padding: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-table--border) {
    border: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background: #fafafa;
}

/* 卡片样式 */
:deep(.el-card__body) {
    padding: 0;
}

/* 分页样式 */
:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-pagination .el-pagination__jump) {
    margin-left: 16px;
}

/* 弹窗样式 */
:deep(.el-dialog__header) {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
    padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .user-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
        padding: 15px;
    }
    
    .search-right {
        margin-left: 0;
        width: 100%;
        justify-content: flex-start;
    }
    
    .search-form .el-form-item {
        margin-bottom: 15px;
    }
    
    .pagination-content {
        gap: 15px;
        padding: 15px;
        flex-direction: row;
        justify-content: flex-end;
    }
    
    .pagination-info {
        text-align: center;
        font-size: 12px;
    }
}
</style>